#!/usr/bin/env python3
#-*- coding:utf-8 -*-


from email.mime.text import MIMEText
from email.header import Header

import smtplib
import prettytable


# Only for generate html table
class MyPrettytable:
    tail = ''
    def __init__(self, head):
        left = '<table>\n<tr>\n'
        for i in head:
            tmp = '<th>' + str(i) + '</th>\n'
            left += tmp

        self.head = left + '</tr>\n'

    def add_row(self, list):
        result = '<tr>\n'
        for i in list:
            tmp = '<td>' + str(i) + '</td>\n'
            result += tmp

        self.tail += result
        self.tail += '</tr>\n'

    def add_row_with_color(self, list, color):
        result = '<tr>\n'
        for i in list:
            tmp = '<td style="color: {};">'.format(color) + str(i) + '</td>\n'
            result += tmp

        self.tail += result
        self.tail += '</tr>\n'

    def get_table(self):
        return self.head + self.tail + '</table>'


def make_table(head, data):
    table = MyPrettytable(head)
    for i in data:
        if i[-1] == 1:
            i[-1] = 'new'
            table.add_row_with_color(i[1:], 'red')
        else:
            i[-1] = ''
            table.add_row(i[1:])

    return table.get_table()


def send_email(addr, msg, subject):
    global s
    msg_from = 'xxx@xx.com'           # 发送方邮箱
    passwd = 'xxxx'             # 填入发送方邮箱的授权码
    msg_to = addr

    mail_massages = MIMEText(_text=msg, _charset='utf-8', _subtype='html')
    mail_massages['From'] = Header(msg_from)
    mail_massages['To'] = Header(msg_to)
    mail_massages['Subject'] = Header(subject)

    try:
        s = smtplib.SMTP_SSL("smtp.163.com", 465)
        s.login(msg_from, passwd)
        s.send_message(mail_massages, msg_from, msg_to)
        print('[INFO] send success to %s' % msg_to)

    except:
        print('[INFO] send email to %s failed > ' % (msg_to))

    finally:
        s.quit()


if __name__ == '__main__':
    t = MyPrettytable([1, 2, 3, 4])
    t.add_row_with_color([2, 3, 4, 5], "red")
    print(t.get_table())
